package com.nsgf.library.ui.monitoring;

import static com.nsgf.library.photopicker.PhotoPreview.EXTRA_PHOTOS;
import static com.nsgf.library.utils.Utils.generateRandomColor;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.ChartDataBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.TransfusionBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityOsmoticPressureChartBinding;
import com.nsgf.library.databinding.ItemChartsTitleBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.photopicker.BigPhotoPagerActivity;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Utils;
import com.nsgf.library.widget.MarkerListView;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.nsgf.library.widget.prckerview.TimePickerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * 渗压监测
 */
public class OsmoticPressureActivity extends BaseActivity implements
        OnChartValueSelectedListener {

    OsmoticPressureStates mState;
    private AccountRequester mAccountRequester;
    protected Typeface tfRegular;
    private ActivityOsmoticPressureChartBinding mBinding;
    private SimpleDataBindingPositionAdapter<ChartDataBean, ItemChartsTitleBinding> mAdapter;

    private float value = 0f;

    YAxis yAxis;
    LibraryInfo item;
    List<LineDataSet> lineDataSet = new ArrayList<>();

    @Override
    protected void initViewModel() {

        mState = getActivityScopeViewModel(OsmoticPressureStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new SimpleDataBindingPositionAdapter<ChartDataBean, ItemChartsTitleBinding>(this, R.layout.item_charts_title, new DiffUtil.ItemCallback() {
            @Override
            public boolean areItemsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                return false;
            }
        }) {
            @Override
            protected void onBindItem(ItemChartsTitleBinding binding, ChartDataBean item, ViewHolder holder, int position) {
                binding.setVm(item);
                setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<ChartDataBean>() {
                    @Override
                    public void onItemClick(int viewId, ChartDataBean item, int position) {
                        mState.chartDataBean.get().get(position).setChartLineDataSet(!item.isChartLineDataSet());
                        invalidate();
                        notifyItemChanged(position);
                    }
                });
            }
        };
        return new DataBindingConfig(R.layout.activity_osmotic_pressure_chart, BR.vm, mState)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private List<TransfusionBean.ListBean> listBeans = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mState.chartDataBean.get().clear();

        ChartDataBean bean = new ChartDataBean();
        bean.setChartTitles("水位");
        bean.setColor(generateRandomColor(0));
        bean.setChartLineDataSet(true);
        mState.chartDataBean.get().add(bean);
        mState.titleBar.set("渗压监测");
        mBinding = (ActivityOsmoticPressureChartBinding) getBinding();

        int orientation = getRequestedOrientation();
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mBinding.titlebar.titleBarRoot.setTextColor(getResources().getColor(R.color.color_1D2129));
            mBinding.titlebar.titleBarBack.setImageResource(R.drawable.ic_nsgf_back);
        }

        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_nsgf_video_big);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarClear.setOnClickListener(this::onClickSecurity);
        mBinding.titlebar.titleBarBack.setOnClickListener(this::onClickSecurity);
        tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        item = (LibraryInfo) getIntent().getSerializableExtra("info");

        /*
          设置数据绑定
         */
        mState.waterRecordsInfoDetails.set(item);

        Calendar calendarStar = Calendar.getInstance();
        calendarStar.set(Calendar.MONTH, calendarStar.get(Calendar.MONTH) - 1);
        mState.startDate.set(ymd.format(calendarStar.getTime()));
        mState.startDateSrc.set(ymd.format(calendarStar.getTime()));
        starTime = calendarStar;


        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        mState.endDateSrc.set(ymd.format(calendar.getTime()));
        mState.endDate.set(ymd.format(calendar.getTime()));
        endTime = calendar;

        mBinding.chart1.setNoDataText("暂无相关数据");

        if (savedInstanceState == null) {
            mAccountRequester.getTransectName(UserInfo.getInstance().getProjectCode());
        }
        mAccountRequester.getTransectNameResult().observe(this, new Observer<ResponseStatus<List<String>>>() {
            @Override
            public void onChanged(ResponseStatus<List<String>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 200) {
                    mState.transectNames.set(listResponseStatus.getData());

                    if (savedInstanceState == null) {
                        if (!Objects.requireNonNull(mState.transectNames.get()).isEmpty())
                            mState.transectName.set(Objects.requireNonNull(mState.transectNames.get()).get(0));
                    }
                    getDatas();
                }
            }
        });

        mAccountRequester.getTransfusionResult().observe(this, new Observer<ResponseStatus<TransfusionBean>>() {
            @Override
            public void onChanged(ResponseStatus<TransfusionBean> beanResponseStatus) {
                getController().dismissLoading();
                if (beanResponseStatus.getResponseCode() == 200) {
                    listBeans = beanResponseStatus.getData().getAnalysis();

                    mState.transfusionBeanState.set(beanResponseStatus.getData());
                    if (listBeans == null) {
                        mBinding.chart1.setData(null);
                        return;
                    }
                    //获取图标最大值
                    for (int i = 0; i < listBeans.size(); i++) {

                        if (i == 0) {
                            value = listBeans.get(i).getWaterLevel();
                        } else {
                            if (value < listBeans.get(i).getWaterLevel()) {
                                value = (listBeans.get(i).getWaterLevel());
                            }
                        }
                    }

                    lineDataSet.clear();
                    initLineDataSet(listBeans);
                    // axis range


                    setData(listBeans);

                    int orientation = getRequestedOrientation();
                    Glide.with(OsmoticPressureActivity.this)
                            .load(APIs.BASE_URL_IMG
                                    + mState.transfusionBeanState.get()
                                    .getBuOsmoticPressureTemplate().getPictureUrl())
                            .thumbnail(0.1f)
                            .dontAnimate()
                            .dontTransform()
                            .override(orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? 800 : 600, orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? 600 : 800)
                            .placeholder(R.drawable.__picker_ic_photo_black_48dp)
                            .error(R.drawable.__picker_ic_broken_image_black_48dp)
                            .into(mBinding.ivNsgfScale);
                } else {
                    showToast(beanResponseStatus.getMsg());
                    initLineDataSet(new ArrayList<>());
                    setData(new ArrayList<>());
                }
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

        mBinding.recyclerView.setLayoutManager(layoutManager);

        mBinding.ivNsgfScale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.llNsgfIndicate.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 数据加载
     */
    private void setData(List<TransfusionBean.ListBean> list) {
        List<Entry> entries = new ArrayList<>();
        if (null == list)
            return;

        for (int i = 0; i < list.size(); i++) {
            Entry entry = new Entry(i, list.get(i).getWaterLevel());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet value = new LineDataSet(entries, "");
        value.setColor(mState.chartDataBean.get().get(0).getColor());
        value.setCircleColor(mState.chartDataBean.get().get(0).getColor());
        value.setLineWidth(1f);
        value.setCircleRadius(1f);
        value.setDrawCircles(false);
        value.setDrawValues(false);
        //设置曲线值的圆点是实心还是空心
        value.setDrawCircleHole(false);
        value.setValueTextSize(10f);
        value.enableDashedHighlightLine(10f, 5f, 0f);
        //设置折线图填充
//        lineDataSet.setDrawFilled(true);
        value.setFormLineWidth(0f);
        value.setFormSize(15.f);
        //设置曲线展示为圆滑曲线（如果不设置则默认折线）
        value.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        value.setFillFormatter(new IFillFormatter() {
            @Override
            public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                return mBinding.chart1.getAxisLeft().getAxisMinimum();
            }
        });

        lineDataSet.add(value);
        LineData lineData = new LineData(lineDataSet.get(0));
        mBinding.chart1.setData(lineData);
        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart1.getAxisLeft().setAxisMaximum(max);
        mBinding.chart1.getAxisLeft().setAxisMinimum(max);
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSet(List<TransfusionBean.ListBean> list) {

        {   // // Chart Style // //

            // background color
            mBinding.chart1.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            mBinding.chart1.setDrawGridBackground(false);
            //是否显示边界
            mBinding.chart1.setDrawBorders(false);
            // disable description text
            mBinding.chart1.getDescription().setEnabled(false);

            // enable touch gestures
            mBinding.chart1.setTouchEnabled(true);

            // set listeners
            mBinding.chart1.setOnChartValueSelectedListener(this);


            // enable scaling and dragging
            mBinding.chart1.setDragEnabled(true);
            mBinding.chart1.setScaleEnabled(true);
            // mBinding.chart1.setScaleXEnabled(true);
            // mBinding.chart1.setScaleYEnabled(true);

            // force pinch zoom along both axis
            mBinding.chart1.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = mBinding.chart1.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setAxisMinimum(0f);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.setLabelRotationAngle(-25);
            xAxis.setLabelCount(Math.min(list.size(), 8), true);
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (list.size() == 0 || value < 0)
                        return "";
                    if ((int) value >= list.size())
                        return "";
                    String tradeDate = list.get((int) value).getDate();
                    return Utils.formatTimeMD(tradeDate);
                }
            });
        }
        mBinding.chart1.setExtraBottomOffset(10f);//修复X轴设置RotationAngle后lable显示不全问题


        yAxis = mBinding.chart1.getAxisLeft();

        // disable dual axis (only use LEFT axis)
        mBinding.chart1.getAxisRight().setEnabled(false);

        yAxis.setLabelCount(10, true);
        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        yAxis.setAxisMinimum(-1f);

        // create marker to display box when values are selected

        mv = new MarkerListView(this, 1, list, mState.chartDataBean.get());
        mv.setChartView(mBinding.chart1);
        mBinding.chart1.setMarker(mv);
        mBinding.chart1.invalidate();

        {   // // Create Limit Lines // //
            LimitLine llXAxis = new LimitLine(9f, "Index 10");
            llXAxis.setLineWidth(4f);
            llXAxis.enableDashedLine(10f, 10f, 0f);
            llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            llXAxis.setTextSize(10f);
            llXAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);
            xAxis.setDrawLimitLinesBehindData(true);

            //xAxis.addLimitLine(llXAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        mBinding.chart1.animateX(500);
        mBinding.chart1.animateY(500);

        // get the legend (only possible after setting data)
        Legend l = mBinding.chart1.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        while (!mBinding.chart1.isFullyZoomedOut()) {

            mBinding.chart1.zoomOut();
        }

    }

    MarkerListView mv;

    private void invalidate() {


        mv.invalidate();
        mv.setChartDataBeans(mState.chartDataBean.get());
        mv.setChartView(mBinding.chart1);
        mBinding.chart1.setMarker(mv);
        mBinding.chart1.invalidate();
        LineData lineData = new LineData();
        for (int i = 0; i < lineDataSet.size(); i++) {
            if (mState.chartDataBean.get().get(i).isChartLineDataSet()) {
                lineData.addDataSet(lineDataSet.get(i));
            }
        }

        if (lineData.getDataSets().size() == 0) {
            mBinding.chart1.setData(null);
            return;
        }

        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart1.getAxisLeft().setAxisMaximum(max);
        mBinding.chart1.getAxisLeft().setAxisMinimum(min);
        mBinding.chart1.setData(lineData);
    }

    private void getDatas() {
        mAccountRequester.analysis(UserInfo.getInstance().getProjectCode(),
                mState.transectName.get(),
                mState.startDate.get(),
                mState.endDate.get());

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOW HIGH", "low: " + mBinding.chart1.getLowestVisibleX() + ", high: " + mBinding.chart1.getHighestVisibleX());
        Log.i("MIN MAX", "xMin: " + mBinding.chart1.getXChartMin() + ", xMax: " + mBinding.chart1.getXChartMax() + ", yMin: " + mBinding.chart1.getYChartMin() + ", yMax: " + mBinding.chart1.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }


    private Calendar starTime;
    private Calendar endTime;

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());


    public static class OsmoticPressureStates extends StateHolder {

        public final State<String> transectName = new State<>("");
        public final State<String> time = new State<>("");
    }

    private int index = 0;

    public class ClickProxy {

        public void openPreview() {

            mBinding.llNsgfIndicate.setVisibility(View.VISIBLE);
        }

        public void screenType() {
            OptionsPickerView<String> mOptionsPickerView = new OptionsPickerView.Builder(OsmoticPressureActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mState.transectName.set(mState.transectNames.get().get(options1));
                    getDatas();
                    index = options1;
                }
            }).build();
            mOptionsPickerView.setPicker(mState.transectNames.get());
            mOptionsPickerView.setSelectOptions(index);
            mOptionsPickerView.show();
        }

        public void screenStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, 1900);
            TimePickerView mTimePickerView = new TimePickerView.Builder(OsmoticPressureActivity.this, (date, v) -> {
                mState.startDate.set(ymd.format(date));
                mState.startDateSrc.set(ymd.format(date));

                getDatas();
                starTime.setTime(date);
            }).isCyclic(false)
                    .setRangDate(calendar, endTime)
                    .setType(type)
                    .setTitleText("开始日期")
                    .setDate(starTime).build();

            mTimePickerView.show();


        }

        public void screenEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
            TimePickerView mTimePickerView = new TimePickerView.Builder(OsmoticPressureActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.endDate.set(ymd.format(date));
                    mState.endDateSrc.set(ymd.format(date));
                    getDatas();
                    endTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(starTime, calendar)
                    .setType(type)
                    .setTitleText("结束日期")
                    .setDate(endTime).build();

            mTimePickerView.show();


        }

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存数据到outState
        outState.putString("startDate", mState.startDate.get());
        outState.putString("endDate", mState.endDate.get());
        outState.putString("startDateSrc", mState.startDateSrc.get());
        outState.putString("endDateSrc", mState.endDateSrc.get());
        outState.putLong("starTime", starTime.getTimeInMillis());
        outState.putLong("endTime", endTime.getTimeInMillis());
        outState.putString("transectName", mState.transectName.get());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // 从savedInstanceState中恢复数据
        if (savedInstanceState != null) {
            // 使用恢复的数据
            mState.startDate.set(savedInstanceState.getString("startDate"));
            mState.endDate.set(savedInstanceState.getString("endDate"));
            mState.startDateSrc.set(savedInstanceState.getString("startDateSrc"));
            mState.endDateSrc.set(savedInstanceState.getString("endDateSrc"));
            starTime.setTimeInMillis(savedInstanceState.getLong("starTime"));
            endTime.setTimeInMillis(savedInstanceState.getLong("endTime"));
            mState.transectName.set(savedInstanceState.getString("transectName"));
            mAccountRequester.getTransectName(UserInfo.getInstance().getProjectCode());
        }
    }

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        if (v.getId() == R.id.title_bar_clear) {

            int orientation = getRequestedOrientation();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mBinding.titlebar.titleBarRoot.setBackgroundColor(getResources().getColor(R.color.white));
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mBinding.titlebar.titleBarRoot.setTextColor(getResources().getColor(R.color.color_1D2129));
                mBinding.titlebar.titleBarBack.setImageResource(R.drawable.ic_nsgf_back);
            }
        }
    }

    @Override
    public void onBackPressed() {
        int orientation = getRequestedOrientation();
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            // Activity 设置为横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else
            super.onBackPressed();

    }
}
